package runner.ui;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.util.EventObject;

/**
 * Created with IntelliJ IDEA.
 * User: AVK
 * Date: 09.11.13
 * Time: 0:21
 * To change this template use File | Settings | File Templates.
 */
public class Editor extends AbstractCellEditor implements
        TreeCellEditor {

    private final Renderer renderer = new Renderer();
    private final JTree theTree;

    public Editor(final JTree tree) {
        theTree = tree;
    }

    @Override
    public Object getCellEditorValue() {
        System.out.println("c");
        final TreeItem panel = renderer.getTheItem();
        final Data  data=
                new Data(panel.label.getText(), panel.checkBox.isSelected());

        return data;
        //return false;
    }

    @Override
    public boolean isCellEditable(final EventObject event) {
        System.out.println("a");
        if (!(event instanceof MouseEvent)) return false;
        final MouseEvent mouseEvent = (MouseEvent) event;

        final TreePath path =
                theTree.getPathForLocation(mouseEvent.getX(), mouseEvent.getY());
        if (path == null) return false;

        final Object node = path.getLastPathComponent();

        if (!(node instanceof DefaultMutableTreeNode)) return false;
        Component component = ((MouseEvent) event).getComponent();
        component.repaint();
        final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;

        final Object userObject = treeNode.getUserObject();
        //System.out.println(userObject);
        return userObject instanceof Data;
        //return true;
    }

    @Override
    public Component getTreeCellEditorComponent(final JTree tree,
                                                final Object value, final boolean selected, final boolean expanded,
                                                final boolean leaf, final int row) {
        System.out.println("b");
        final Component editor =
                renderer.getTreeCellRendererComponent(tree, value, true, expanded, leaf,
                        row, true);



        final ItemListener itemListener = new ItemListener() {

            @Override
            public void itemStateChanged(final ItemEvent itemEvent) {
                if (stopCellEditing()) {
                    fireEditingStopped();
                }
            }
        };
        if (editor instanceof TreeItem) {
            System.out.println("yo");
            final TreeItem panel = (TreeItem) editor;
            panel.checkBox.addItemListener(itemListener);

        }
        return editor;
    }

}
